Memory management involves the allocation of portions of memory to programs upon request, and freeing allocated memory for reuse when the program no longer needs the memory. Inefficient or incorrect usage of memory can degrade program performance or can cause programs to crash. Similarly, failing to free allocated memory or improperly freeing memory can degrade program performance or can cause programs to crash.
The term “garbage collection” is often used to refer to a form of automatic memory management in which a garbage collector reclaims memory that is no longer in use. Garbage collection is a technique that is frequently used in virtual machine environments. In contrast, manual memory management relies on the use of instructions in the program to ask the operating system to allocate memory and to de-allocate unused memory. Commonly used languages that manually manage memory include native languages such as C and C++.
Manual memory management can introduce several general classes of errors into a program. For example, a memory leak can occur if allocated portions of memory are not freed when the program is done with them. A memory leak can be relatively harmless (e.g., in a short-running program where the operating system de-allocates program resources when the program ends), or can cause a program to crash if the memory leak exhausts available memory. Even if the memory leak does not exhaust available memory and does not cause the program to crash, program performance can be degraded because, for example, lack of sufficient available memory forces data to be swapped out to disk. Another type of memory management error occurs when allocated space is freed more than once or if a pointer to unallocated memory is freed. This kind of error can corrupt data structures or can improperly free a portion of memory that has since been used by another program construct. If a pointer that points to freed memory is used after the memory is freed, unpredictable results can ensue. Memory overuse occurs when instructions in the program allocate too much memory so that there is not enough memory left for the program to run efficiently.